package com.lovezy.platform.member.service;

import com.google.common.collect.ImmutableMap;
import com.lovezy.platform.common.extend.ExtendService;
import com.lovezy.platform.core.jwt.JwtUtil;
import com.lovezy.platform.core.spring.SpringContext;
import com.lovezy.platform.discuz.vo.DiscuzMemberVo;
import com.lovezy.platform.member.enums.LoginSourceEnum;
import com.lovezy.platform.member.vo.MemberVo;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;
import java.util.Map;

/**
 * 登陆后返回信息类
 * Created by jin on 2017/11/5.
 */
@Getter
@Setter
public class LoginResponse {

    private MemberVo member;

    private Byte source;

    private Boolean isBind;

    private Map<String, Object> payload;

    private LoginResponse() {
    }

    public static LoginResponse siteLogin(MemberVo memberVo) {
        LoginResponse response = new LoginResponse();
        String token = createToken(memberVo.getMemberId());
        memberVo.setToken(token);
        response.setMember(memberVo);
        response.setSource(LoginSourceEnum.SITE.getValue());
        return response;
    }

    public static LoginResponse dzLogin(DiscuzMemberVo member) {
        LoginResponse response = new LoginResponse();
        response.setSource(LoginSourceEnum.DISCUZ.getValue());
        response.setPayload(ImmutableMap.of("discuzMember", member));
        response.setIsBind(false);
        return response;
    }

    public static LoginResponse qqLogin(MemberVo member) {
        LoginResponse response = new LoginResponse();
        response.setSource(LoginSourceEnum.QQ.getValue());
        response.setIsBind(member != null);
        response.setMember(member);
        return response;
    }


    private static String createToken(String mid) {
        ExtendService service = SpringContext.getContext().getBean(ExtendService.class);
        String tokenId = service.modifyToken(mid);
        Map<String, Object> claims = ImmutableMap.of("mid", mid, "token", tokenId, "time", new Date());
        return JwtUtil.createJavaWebToken(claims);
    }
}
